<template>
  <div>
    <BasicTable
      @register="registerTable"
      :rowSelection="{ type: 'checkbox', selectedRowKeys: checkedKeys, onChange: onSelectChange }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="getTableAction(record)"
        /></template>
      </template>
      <template #toolbar>
        <a-button
          class="mr-2"
          :disabled="!checkedRows.length"
          @click="handlePublishExp(2, checkedRows)"
          >批量发布体验</a-button
        >
        <a-button
          class="mr-2"
          :disabled="!checkedRows.length || !expVersion"
          @click="handleSubmitReview(2, checkedRows)"
          >批量提交审核</a-button
        >
        <a-button
          class="mr-2"
          :disabled="!checkedRows.length || !releaseVersion"
          @click="handleVBack(2, checkedRows)"
          >批量回滚</a-button
        >
        <a-button
          class="mr-2"
          :disabled="!checkedRows.length || !expVersion || auditStatus != 0"
          @click="handlePublishOnline(2, checkedRows)"
          >批量发布线上</a-button
        >
        <a-button class="mr-2" @click="handleRefresh">刷新状态</a-button>
      </template>
      <template #expVersion="{ column, record }">
        <Button v-if="record.expVersion" type="link" size="small" @click="handlePreview(record)"
          >预览</Button
        >
        <span>{{ record.expVersion }}</span>
      </template>
      <template #auditVersion="{ column, record }">
        <Button v-if="record.auditVersion" type="link" size="small" @click="handleVBack(1, record)"
          >回滚</Button
        >
        <span>{{ record.auditVersion }}</span>
      </template>
    </BasicTable>
    <PublishExpModal @register="register" @reload="handleRefresh" />
    <PublishOnlineModal @register="registerOnline" @reload="handleRefresh" />
    <SubmitReviewModal @register="registerSubmitReview" @reload="handleRefresh" />
    <ExpImgModal @register="registerExpImg" />
    <VersionBackModal @register="registerVBack" @reload="handleRefresh" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import PublishExpModal from './components/publishExpModal.vue';
  import PublishOnlineModal from './components/publishOnlineModal.vue';
  import SubmitReviewModal from './components/submitReviewModal.vue';
  import VersionBackModal from './components/versionBackModal.vue';
  import ExpImgModal from './components/expImgModal.vue';
  import { versionPageList, releaseVersionDown, expVersionDown } from '@/api/version';
  import { getBasicColumns } from './tableData';
  import { useModal } from '@/components/Modal';
  import { Button } from '@/components/Button';
  import { IVersionPageListResult } from '@/api/version/type';
  import Dictionary from '@/utils/dictionary';
  import { AuditStatusEnum } from '@/utils/enum';
  import { ref } from 'vue';

  const dicts = Dictionary.getLocalMulti(['auditStatus']);
  const checkedKeys = ref<(string | number)[]>([]);
  const checkedRows = ref<IVersionPageListResult[]>([]);
  const releaseVersion = ref();
  const expVersion = ref();
  const auditStatus = ref();

  function onSelectChange(
    selectedRowKeys: (string | number)[],
    selectedRows: IVersionPageListResult[],
  ) {
    console.log('selectedRowKeys', selectedRowKeys, selectedRows);
    checkedKeys.value = selectedRowKeys;
    checkedRows.value = selectedRows;
  }

  const reset = async () => {
    checkedKeys.value = [];
    checkedRows.value = [];
  };

  const [registerTable, { reload }] = useTable({
    title: '',
    api: versionPageList,
    columns: getBasicColumns(),
    formConfig: {
      labelWidth: 100,
      schemas: [
        {
          field: `releaseVersion`,
          label: `线上版本`,
          component: 'ApiSelect',
          colProps: {
            span: 4,
          },
          componentProps: {
            api: () => releaseVersionDown().then(res=>{
                return res.map(item=>{
                    return {
                        label: item,
                        value: item
                    }
                })
            }),
            placeholder: '请选择线上版本号',
            onChange: (e) => {
              releaseVersion.value = e;
              setTimeout(() => {
                handleRefresh();
              }, 100);
            },
          },
        },
        {
          field: `expVersion`,
          label: `体验版本`,
          component: 'ApiSelect',
          colProps: {
            span: 4,
          },
          componentProps: {
            api: () => expVersionDown().then(res=>{
                return res.map(item=>{
                    return {
                        label: item,
                        value: item
                    }
                })
            }),
            placeholder: '请选择体验版本号',
            onChange: (e) => {
              expVersion.value = e;
              setTimeout(() => {
                handleRefresh();
              }, 100);
            },
          },
        },
        {
          field: `auditStatus`,
          label: `审核状态`,
          component: 'Select',
          colProps: {
            span: 4,
          },
          componentProps: {
            fieldNames: { label: 'dictLabel', value: 'dictValue' },
            options: dicts.auditStatus,
            placeholder: '请选择审核状态',
            onChange: (e) => { 
              auditStatus.value = e;
              setTimeout(() => {
                handleRefresh();
              }, 100);
            },
          },
        },
        {
          field: `organizationName`,
          label: `机构名称`,
          component: 'Input',
          colProps: {
            span: 4,
          },
          componentProps: {
            placeholder: '请输入机构名称',
          },
        },
        {
          field: `wechatAppName`,
          label: `小程序名称`,
          component: 'Input',
          colProps: {
            span: 4,
          },
          componentProps: {
            placeholder: '请输入小程序名称',
          },
        },
      ],
      resetFunc: async () => {
        reset();
        releaseVersion.value = undefined;
        expVersion.value = undefined;
        auditStatus.value = undefined;
      },
    },
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    showIndexColumn: true,
    clickToRowSelect: false,
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
    },
    afterFetch: (data: IVersionPageListResult[]) => {
      return data.map((item) => {
        return {
          ...item,
          auditStatus: dicts.auditStatus.find((v) => v.dictValue == item.auditStatus)?.dictLabel,
          auditStatusId: item.auditStatus,
        };
      });
    },
  });

  function getTableAction(record: IVersionPageListResult) {
    let action: any = [];
    if (!record.organizationName) return action;

    action.push({
      label: '发布体验',
      onClick: handlePublishExp.bind(null, 1, record),
    });

    // let SubmitReviewStatus = [1, 2, 4];
    let SubmitReviewStatus = [AuditStatusEnum.REJECT, AuditStatusEnum.DOING, AuditStatusEnum.DELAY];
    if (!SubmitReviewStatus.includes(record.auditStatusId as number) && record.expVersion) {
      action.push({
        label: '提交审核',
        onClick: handleSubmitReview.bind(null, 1, record),
      });
    }

    if (record.auditStatusId === AuditStatusEnum.REJECT) {
      action.push({
        label: '重新提交',
        onClick: handleSubmitReview.bind(null, 1, record),
      });
    }

    if (record.auditStatusId === AuditStatusEnum.SUCCESS && record.auditId != -1) {
      action.push({
        label: '发布线上',
        onClick: handlePublishOnline.bind(null, 1, record),
      });
    }

    return action;
  }

  const [register, { openModal }] = useModal();
  const [registerOnline, { openModal: openOnlineModal }] = useModal();
  const [registerSubmitReview, { openModal: openSubmitReviewModal }] = useModal();
  const [registerExpImg, { openModal: openExpImgModal }] = useModal();
  const [registerVBack, { openModal: openVBackModal }] = useModal();

  function handlePublishExp(type: number, row) {
    openModal(true, {
      type,
      row,
    });
  }

  function handlePublishOnline(type: number, row) {
    openOnlineModal(true, {
      type,
      row,
    });
  }

  function handlePreview(record) {
    openExpImgModal(true, {
      record,
    });
  }

  function handleSubmitReview(type: number, row) {
    openSubmitReviewModal(true, {
      type,
      row,
    });
  }

  function handleVBack(type: number, row) {
    openVBackModal(true, {
      type,
      row,
    });
  }

  function handleRefresh() {
    reload();
    reset();
  }
</script>

<style lang="less" scoped>
  .btns {
    padding: 20px;
  }
</style>
